﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.BusinessLogic.Services;
using NopSolutions.NopCommerce.BusinessLogic.Infrastructure;
using NopSolutions.NopCommerce.BusinessLogic.Model;
using NopSolutions.NopCommerce.BusinessLogic.SEO;

namespace NopSolutions.NopCommerce.Web.Templates.Categories
{
    public partial class BundlesCategoryTemplate : BaseNopFrontendUserControl
    {
        private ICategoryService _categoryService;
        private IProductService _productService;
        private IPictureService _pictureService;
        private IShoppingCartService _shoppingCartService;
        private Category _category;

        private ISettingService _settingService;

        private int _productImageSize = 125;

        public BundlesCategoryTemplate() {
            _categoryService = IoC.Resolve<ICategoryService>();
            _productService = IoC.Resolve<IProductService>();
            _pictureService = IoC.Resolve<IPictureService>();
            _shoppingCartService = IoC.Resolve<IShoppingCartService>();
            _settingService = IoC.Resolve<ISettingService>();
        }

        protected override void OnInit(EventArgs e) {
            base.OnInit(e);

            Load += new EventHandler(BundlesCategoryTemplate_Load);
            ddlSorting.SelectedIndexChanged += new EventHandler(ddlSorting_SelectedIndexChanged);
            rptProducts.ItemDataBound += new RepeaterItemEventHandler(rptProducts_ItemDataBound);
        }

        #region Events

        void BundlesCategoryTemplate_Load(object sender, EventArgs e) {
            if (!IsPostBack) {
                FillDropDowns();
                BindData();
            }
        }

        void ddlSorting_SelectedIndexChanged(object sender, EventArgs e) {
            string url = CommonHelper.GetThisPageUrl(true);
            url = CommonHelper.ModifyQueryString(url, "orderby=" + ddlSorting.SelectedItem.Value, null);
            Response.Redirect(url);
        }

        void rptProducts_ItemDataBound(object sender, RepeaterItemEventArgs e) {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
                var product = e.Item.DataItem as Product;
                if (product != null) {
                    var lnkImageLink = e.Item.FindControl("lnkImageLink") as HyperLink;
                    var litBundleTitle = e.Item.FindControl("litBundleTitle") as Literal;
                    var litShortDescription = e.Item.FindControl("litShortDescription") as Literal;
                    var lnkBundleDetails = e.Item.FindControl("lnkBundleDetails") as HyperLink;

                    if (product.DefaultPicture != null) {
                        lnkImageLink.ImageUrl = _pictureService.GetPictureUrl(product.DefaultPicture, this.ProductImageSize, true);
                        lnkImageLink.ToolTip = String.Format(GetLocaleResourceString("Media.Product.ImageLinkTitleFormat"), product.LocalizedName);
                        lnkImageLink.Text = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
                    }
                    else {
                        lnkImageLink.ImageUrl = _pictureService.GetDefaultPictureUrl(ProductImageSize);
                        lnkImageLink.ToolTip = String.Format(GetLocaleResourceString("Media.Product.ImageLinkTitleFormat"), product.LocalizedName);
                        lnkImageLink.Text = String.Format(GetLocaleResourceString("Media.Product.ImageAlternateTextFormat"), product.LocalizedName);
                    }

                    litBundleTitle.Text = product.LocalizedName;
                    litShortDescription.Text = product.LocalizedShortDescription;
                    lnkBundleDetails.NavigateUrl = SEOHelper.GetProductUrl(product);
                }
            }
        }

        protected void btnAddToCart_Click(object sender, CommandEventArgs e) {
            int productId = Convert.ToInt32(e.CommandArgument);
            int productVariantId = 0;
            if (_productService.DirectAddToCartAllowed(productId, out productVariantId)) {
                var addToCartWarnings = _shoppingCartService.AddToCart(ShoppingCartTypeEnum.ShoppingCart, productVariantId, string.Empty, decimal.Zero, 1);
                if (addToCartWarnings.Count == 0) {
                    bool displayCart = _settingService.GetSettingValueBoolean("Display.Products.DisplayCartAfterAddingProduct");
                    if (displayCart) {
                        //redirect to shopping cart page
                        Response.Redirect(SEOHelper.GetShoppingCartUrl());
                    }
                    else {
                        //display notification message
                        this.DisplayAlertMessage(GetLocaleResourceString("Products.ProductHasBeenAddedToTheCart"));
                    }
                }
                else {
                    string productURL = SEOHelper.GetProductUrl(productId);
                    Response.Redirect(productURL);
                }
            }
            else {
                string productURL = SEOHelper.GetProductUrl(productId);
                Response.Redirect(productURL);
            }
        }

        #endregion

        #region Methods

        private void BindData() {
            if (Category != null) {
                litTitle.Text = Category.LocalizedName;
                litDescription.Text = Category.LocalizedDescription;

                //page size
                int totalRecords = 0;
                int pageSize = 10;
                if (Category.PageSize > 0) {
                    pageSize = Category.PageSize;
                }

                var products = _productService.GetAllProducts(CategoryId, 0, 0, null, pageSize, CurrentPageIndex, out totalRecords);
                if (products != null && products.Count > 0) {
                    productsPager.PageSize = pageSize;
                    productsPager.TotalRecords = totalRecords;
                    productsPager.PageIndex = this.CurrentPageIndex;

                    rptProducts.Visible = true;
                    rptProducts.DataSource = products;
                    rptProducts.DataBind();
                }
                else {
                    rptProducts.Visible = false;
                }
            }
        }

        protected void FillDropDowns() {
            if (_settingService.GetSettingValueBoolean("Common.AllowProductSorting")) {
                ddlSorting.Items.Clear();

                var ddlSortPositionItem = new ListItem(GetLocaleResourceString("ProductSorting.Position"), ((int)ProductSortingEnum.Position).ToString());
                ddlSorting.Items.Add(ddlSortPositionItem);

                var ddlSortNameItem = new ListItem(GetLocaleResourceString("ProductSorting.Name"), ((int)ProductSortingEnum.Name).ToString());
                ddlSorting.Items.Add(ddlSortNameItem);

                var ddlSortPriceItem = new ListItem(GetLocaleResourceString("ProductSorting.Price"), ((int)ProductSortingEnum.Price).ToString());
                ddlSorting.Items.Add(ddlSortPriceItem);

            }
            else {
                pnlSorting.Visible = false;
            }
        }

        #endregion

        #region Properties

        public int CategoryId {
            get {
                return CommonHelper.RouteStringInt("categoryId");
            }
        }

        public new ICategoryService CategoryService {
            get { return _categoryService; }
        }

        public new IProductService ProductService {
            get { return _productService; }
        }

        public new IPictureService PictureService {
            get { return _pictureService; }
        }

        public Category Category {
            get {
                if (_category == null)
                    _category = _categoryService.GetCategoryById(CategoryId);

                return _category;
            }
        }

        public ISettingService SettingService {
            get { return _settingService; }
        }

        public int ProductImageSize {
            get { return SettingService.GetSettingValueInteger("Media.Product.ThumbnailImageSize", _productImageSize); }
            set { _productImageSize = value; }
        }

        public int CurrentPageIndex {
            get {
                int _pageIndex = CommonHelper.QueryStringInt(productsPager.QueryStringProperty);
                _pageIndex--;
                if (_pageIndex < 0)
                    _pageIndex = 0;
                return _pageIndex;
            }
        }

        #endregion
    }
}